package com.haust.community.controller;

import com.haust.community.pojo.DiscussPost;
import com.haust.community.service.ElasticSearchService;
import com.haust.community.service.LikeService;
import com.haust.community.service.UserService;
import com.haust.community.utils.CommunityConstant;
import com.haust.community.vo.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: csp1999
 * @Date: 2020/12/01/11:20
 * @Description: 搜索操作的 Controller
 */
@Controller
public class SearchController implements CommunityConstant {

    @Autowired
    private ElasticSearchService elasticSearchService;

    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;

    /**
     * search?keyword=xxx
     * 根据搜索关键词搜索帖子
     *
     * @param keyword
     * @param page
     * @param model
     * @return
     */
    @RequestMapping(path = "/search", method = RequestMethod.GET)
    public String search(String keyword, Page page, Model model) {
        // 搜索帖子
        List<DiscussPost> searchResult =
                elasticSearchService.searchDiscussPost(keyword, page.getCurrent() - 1, page.getLimit());

        // 聚合数据集合
        List<Map<String, Object>> discussPosts = new ArrayList<>();
        if (searchResult != null) {
            for (DiscussPost post : searchResult) {
                Map<String, Object> map = new HashMap<>();
                // 帖子信息
                map.put("post", post);
                // 作者信息
                map.put("user", userService.findUserById(post.getUserId()));
                // 点赞数量
                map.put("likeCount", likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId()));

//                System.out.println(map);
                // map添加到聚合数据的集合中
                discussPosts.add(map);
            }
        }
        // 聚合数据集合存入model
        model.addAttribute("discussPosts", discussPosts);
        // 搜索关键字存入model
        model.addAttribute("keyword", keyword);

        // 分页信息
        page.setPath("/search?keyword=" + keyword);// 查询路径
        page.setRows(searchResult == null ? 0 : (int) searchResult.size());// 查到的数据数量

        return "/site/search";
    }
}
